package chapter02.part07;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.regex.MatchResult;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * 找出一个或多个匹配的子字符串
 * 
 * 定位一个网页上的所有超文本链接
 * 
 * @author insight
 * @since 2021/8/28
 */
public class HrefMatch {
    public static void main(String[] args) throws IOException {
        String urlStr = "https://www.w3school.com.cn/";

        // read contents
        InputStream in = new URL(urlStr).openStream();
        String input = new String(in.readAllBytes(), StandardCharsets.UTF_8);
        
        // search all occurrences of pattern
        // <a href = "">
        String patternStr = "<a\\s+href\\s*=\\s*(\"[^\"]*\"|[^\\s>]*)\\s*>";
        Pattern pattern = Pattern.compile(patternStr, Pattern.CASE_INSENSITIVE);
        
        // 一般使用 find() 来找出匹配的子串
        Matcher matcher = pattern.matcher(input);
        while (matcher.find()) {
            int st = matcher.start();
            int ed = matcher.end();
            System.out.println(matcher.group());
        }
        
        // 也可以使用 results() 获取一个 Stream<MatchResult>
        pattern.matcher(input)
                .results()
                .map(MatchResult::group)
                .forEach(System.out::println);
        
        
        // 如果是文件 使用 Scanner.findAll()
        // Scanner in = new Scanner(path, StandardCharsets.UTF_8);
        // Stream<String> words = in.findAll("\\pL+").map(MatchResult::group);
    }
}